﻿using TulingMember.Core;

namespace TuLing.Blazor.Services
{
    public class SaleOrderDetailService
    {
        private readonly DefaultDbContext _context;
        public SaleOrderDetailService(DefaultDbContext context)
        {
            _context = context;
        }

        public List<SaleOrderDetail> Search(long orderId)
        {
            return _context.SaleOrderDetails.Where(d => d.SaleOrderId == orderId).ToList();
        }

        public SaleOrderDetail? Get(long id)
        {
            return _context.SaleOrderDetails.FirstOrDefault(d => d.Id == id);
        }

        public SaleOrderDetail? Save(SaleOrderDetail input)
        {
            if (input.Id == 0)
            {
                _context.SaleOrderDetails.Add(input);
            }
            else
            {
                _context.SaleOrderDetails.Update(input);
            }
            _context.SaveChanges();
            return input;
        }

        public void Delete(long id)
        {
            var detail = _context.SaleOrderDetails.FirstOrDefault(d => d.Id == id);
            if (detail == null)
            {
                throw new Exception("明细不存在");
            }
            _context.SaleOrderDetails.Remove(detail);
            _context.SaveChanges();
        }
    }
}
